﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;

using Gurucore.Framework.Test;

namespace Gurucore.TestUI
{
	public partial class MainForm : Form
	{
		public MainForm()
		{
			InitializeComponent();
		}

		private void MainForm_Load(object sender, EventArgs e)
		{
			TestConfiguration oTestCfg = Gurucore.Framework.Core.Application.GetInstance().GetGlobalSharedObject<TestConfiguration>();
			foreach (string sTestTarget in oTestCfg.TestTarget)
			{
				TestInspector oInspector = new TestInspector(sTestTarget);
				
				TreeNode oAssemblyNode = new TreeNode(oInspector.GetAssembly().GetName().Name);
				oAssemblyNode.Tag = oInspector.GetAssembly();
				oAssemblyNode.ImageIndex = oAssemblyNode.SelectedImageIndex = 2;
				tvwTestSuite.Nodes.Add(oAssemblyNode);

				List<Type> arrTestClasses = oInspector.GetTestClasses();
				foreach (Type oTestClass in arrTestClasses)
				{
					TreeNode oClassNode = new TreeNode(oTestClass.Name);
					oClassNode.Tag = oTestClass;
					oClassNode.ImageIndex = oClassNode.SelectedImageIndex = 2;
					oAssemblyNode.Nodes.Add(oClassNode);

					List<MethodInfo> arrTestMethods = oInspector.GetTestMethods(oTestClass);
					foreach (MethodInfo oTestMethod in arrTestMethods)
					{
						TreeNode oMethodNode = new TreeNode(oTestMethod.Name);
						oMethodNode.Tag = oTestMethod;
						oMethodNode.ImageIndex = oMethodNode.SelectedImageIndex = 2;
						oClassNode.Nodes.Add(oMethodNode);
					}
				}
			}
			tvwTestSuite.ExpandAll();
		}

		private void tvwTestSuite_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
		{
			TreeNode oNode = e.Node;
			TestRunner oTestRunner = new TestRunner();

			if (oNode.Tag is Assembly)
			{
			}
			else if (oNode.Tag is Type)
			{
			}
			else if (oNode.Tag is MethodInfo)
			{
				TestSuite oTestSuite = (TestSuite)Activator.CreateInstance(((MethodInfo)oNode.Tag).DeclaringType);
				TestResult oTestResult = oTestRunner.Run((MethodInfo)oNode.Tag, oTestSuite);
				if (oTestResult.Fatal)
				{
					oNode.SelectedImageIndex = oNode.ImageIndex = 0;
					txtErrors.Text += "\r\n" + oTestResult.ErrorMessage;
					txtErrors.SelectionStart = txtErrors.Text.Length;
					txtErrors.ScrollToCaret();
				}
				else
				{
					if (oTestResult.Pass)
					{
						oNode.SelectedImageIndex = oNode.ImageIndex = 1;
						txtTime.Text = oTestResult.Runtime.ToString();
					}
					else
					{
						oNode.SelectedImageIndex = oNode.ImageIndex = 0;
					}
				}
			}
		}
	}
}
